<template>
  <view class="classification-wrapper">
    <view class="order-search">
      <u-search placeholder="请输入分类名称" v-model="keyword" clearable bgColor="#fff" borderColor="#e5e5e5"
        :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>
      <view class="flex-row" style="flex:2">
        <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
        <!-- <u-button :plain="true" text="重置" @click="handleReset"></u-button> -->
      </view>
    </view>
    <view class="classification-table">
      <view class="two-level-table">
        <uni-table border stripe :loading="loading" class="fixed-height-table">
          <!-- 表头 -->
          <uni-tr type="th">
            <uni-th>分类名称</uni-th>
            <uni-th>分类图标</uni-th>
            <uni-th>排序</uni-th>
            <uni-th  width="200">关联商品</uni-th>
            <uni-th>状态</uni-th>
            <uni-th>创建时间</uni-th>
            <uni-th>最近更新时间</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>

          <!-- 第一级：父分类 -->
          <template v-for="(parent, pIndex) in tableData" :key="parent.id || pIndex">
            <!-- 父分类行 -->
            <uni-tr>
              <uni-td>
                <view class="parent-node">
                  <!-- 展开/折叠按钮（有子分类时显示） -->
                  <view class="expand-icon" @click.stop="parent.expanded = !parent.expanded" v-if="hasChildren(parent)">
                    <u-icon name="play-right-fill" size="14" color="#8590B3 " v-if="!parent.expanded"></u-icon>
                    <u-icon name="arrow-down-fill" size="14" color="#8590B3 " v-if="parent.expanded"></u-icon>
                  </view>
                  <!-- 父分类名称 -->
                  <text class="parent-name">{{ parent.categoryName }}</text>
                </view>
              </uni-td>
              <uni-td>
                <image :src="parent.categoryIcon" mode="" style="width:32px;height: 32px;vertical-align: middle;">
                </image>
              </uni-td>
              <uni-td>{{ parent.sortOrder }}</uni-td>
              <uni-td>
                <view v-if="parent.products &&parent.products.length>0">
                  {{ parent.products.map(item => item.name).join('，') }}
                </view>
              </uni-td>
              <uni-td>
                <u-tag text="启用" type="success" plain v-if="parent.isActive == 1" size="mini"> </u-tag>
                <u-tag text="禁用" type="error" plain v-else size="mini"></u-tag>
              </uni-td>
              <uni-td>{{ parent.createDate || '—' }}</uni-td>
              <uni-td>{{ parent.lastUpdateDate || '—' }}</uni-td>
              <uni-td align="center">
                <view class="operation-btns">
                  <view class="btn" @click.stop="handleEdit(parent)">
                    编辑
                  </view>
                  <view class="btn" @click.stop="handleDel(parent)">
                    删除
                  </view>
                  <view class="btn" @click.stop="toggleStatus(parent)">
                    {{ parent.isActive == 1 ? '禁用' : '启用' }}
                  </view>
                </view>
              </uni-td>
            </uni-tr>

            <!-- 第二级：子分类（仅在父分类展开时显示） -->
            <template v-if="parent.expanded && hasChildren(parent)">
              <uni-tr v-for="(child, cIndex) in parent.children" :key="child.id || cIndex">
                <uni-td>
                  <view class="child-node">
                    <!-- 子分类名称（固定缩进，无需展开按钮） -->
                    <text class="child-name">{{ child.categoryName }}</text>
                  </view>
                </uni-td>
                <uni-td>
                  <image :src="child.categoryIcon" mode="" style="width:32px;height: 32px;vertical-align: middle;">
                  </image>
                </uni-td>
                <uni-td>{{ child.sortOrder }}</uni-td>
                <uni-td><view v-if="child.products &&child.products.length>0">
                  {{ child.products.map(item => item.name).join('，') }}
                </view></uni-td>
                <uni-td>
                  <u-tag text="启用" type="success" plain v-if="child.isActive == 1"> </u-tag>
                  <u-tag text="禁用" type="error" plain v-else></u-tag>
                </uni-td>
                <uni-td>{{ child.createDate || '—' }}</uni-td>
                <uni-td>{{ child.lastUpdateDate || '—' }}</uni-td>
                <uni-td align="center">
                  <view class="operation-btns">
                    <view class="btn" @click.stop="handleEdit(child)">
                      编辑
                    </view>
                    <view class="btn" @click.stop="handleDel(child)">
                      删除
                    </view>
                    <view class="btn" @click.stop="toggleStatus(child)">
                      {{ child.isActive == 1 ? '禁用' : '启用' }}
                    </view>
                  </view>
                </uni-td>
              </uni-tr>
            </template>
          </template>
        </uni-table>

        <!-- 批量操作按钮 -->
      </view>
      <view class="detail-foot">
        <view class="foot-btn" style="margin: auto">
          <view class="order-btn" @click="contentClick">新增分类</view>
          <!-- <view class="order-btn1">调整排序</view> -->
        </view>
      </view>
    </view>
  </view>
  <u-popup :show="show" @close="popupCancel" :round="10" mode="center">
    <view class="popup-cons">
      <view class="applyfor-tit">
        {{showTitle}}
      </view>
      <view class="applyfor-info">
        {{showInfo}}
      </view>
      <view class="button-group">
        <button class="cancel-btn" @click="popupCancel">取消</button>
        <button class="pay-btn" @click="popupSure">确认</button>
      </view>
    </view>
  </u-popup>
  <u-popup :show="showSure" @close="popupSures" :round="10" mode="center">
    <view class="popup-cons">
      <view class="applyfor-image">
        <image src="../../../static/imgs/erro.png" mode=""></image>
      </view>
      <view class="applyfor-green" style="color:#F32F1D ">
        {{showTitle}}
      </view>
      <view class="applyfor-info">
        {{showInfo}}
      </view>
      <view class="button-group">
        <button class="pay-btn" @click="popupSures">确认</button>
      </view>
    </view>
  </u-popup>
</template>
<script setup>
  import {
    ref,
    computed,
    onMounted
  } from 'vue'
  import {
    getTreeCategory,
    deleteSassCategoryByIds,
    updateSassCategoryById,
  } from '@/requests/apis/products'
  let show = ref(false)
  let showSure = ref(false)
  let showType = ref()
  let showTitle = ref()
  let showInfo = ref()
  let itemData = ref()
  const tableData = ref([])
  let keyword = ref()
  let loading = ref(true)
  const getData = async () => {
    loading.value = true
    let res = await getTreeCategory({
      keyword: keyword.value,
    })
    tableData.value = res.Result || []
    loading.value = false
    console.log(res, '111111')
  }
  onMounted(() => {
    console.log('1223344')
    getData()
  })

  // 检查是否有子分类
  const hasChildren = (item) => {
    return Array.isArray(item.children) && item.children.length > 0
  }

  // 控制全部展开/折叠
  const allExpanded = ref(false)
  const toggleAllExpand = () => {
    allExpanded.value = !allExpanded.value
    // 批量更新所有父分类的展开状态
    tableData.value.forEach((parent) => {
      parent.expanded = allExpanded.value
    })
  }
  const handleSearch = () => {
    console.log("132235")
    getData()
  }
  const handleReset = () => {
    keyword.value = ''
    getData()
  }
  // 编辑操作
  const handleEdit = (item) => {
    console.log('编辑分类:', item)
    uni.navigateTo({
      url: `/pages/products/classification/formAdd?infoList=${encodeURIComponent(
      JSON.stringify(item),
    )}`,
    })
  }
  // 删除
  const handleDel = (item) => {
    show.value = true;
    showType.value = 1;
    showTitle.value = '确认删除'
    showInfo.value = `是否确认删除分类“${item.categoryName}”，分类删除后将不可恢复。`
    itemData.value = item
  }

  // 切换状态（启用/禁用）
  const toggleStatus = (item) => {
    show.value = true;
    showType.value = 2;
    showTitle.value = item.isActive === 1 ? '确认禁用' : '确认启用'
    showInfo.value = item.isActive === 1 ? `是否确认禁用分类“${item.categoryName}”，禁用后分类及其商品将不在展示。` :
      `是否确认启用分类“${item.categoryName}”，启用后分类及其商品将在点餐前台展示。`
    let data = JSON.parse(JSON.stringify(item))
    data.isActive = data.isActive === 1 ? 0 : 1
    itemData.value = data

  }
  // 弹窗取消
  const popupCancel = () => {
    show.value = false
  }
  // 弹窗确认
  const popupSure = () => {
    show.value = false
    if (showType.value == 1) {
      deleteSassCategoryByIds({
          ids: [itemData.value.categoryId],
        })
        .then((a) => {
          uni.showToast({
            title: '删除成功',
            icon: 'none',
            duration: 2000,
            success() {
              setTimeout(() => {
                getData('refresh')
              }, 2000)
            },
          })
        })
        .catch((error) => {
          uni.hideLoading()
          showSure.value = true;
          showTitle.value = '删除失败'
          showInfo.value = '当前分类下还存在商品，请先移除这些商品。'
        })
    } else {
      let tit = itemData.value.isActive === 1 ? '启用' : '禁用'
      updateSassCategoryById({
          categoryName: itemData.value.categoryName,
          categoryId: itemData.value.categoryId,
          sortOrder: itemData.value.sortOrder,
          isActive: itemData.value.isActive,
          description: itemData.value.description,
          parentId: itemData.value.parentId,
          categoryIcon: itemData.value.categoryIcon,
        })
        .then((a) => {
          uni.showToast({
            title: `${tit}成功`,
            icon: 'none',
            duration: 2000,
            success() {
              setTimeout(() => {
                getData()
              }, 2000)
            },
          })
        })
        .catch((error) => {
          uni.hideLoading()
        })
    }
  }
  //二级弹窗确认
  const popupSures = () => {
    showSure.value = false;

  }
  const contentClick = () => {
    uni.navigateTo({
      url: `/pages/products/classification/formAdd`,
    })
  }
</script>
<style lang="scss">
  .classification-wrapper {
    display: flex;
    // flex: 1;
    overflow: hidden;
    flex-direction: column;
    height: 100%;

    .fixed-height-table {
      :deep(.uni-table-td) {
        // align-items: center;
        // display: flex;
      }
    }


    .order-search {
      display: flex;
      background-color: #fff;
      margin: 10px;
      padding: 12px 145px 12px 20px;
      box-sizing: border-box;

      :deep(button) {
        width: 74px;
        height: 38px;
        margin-right: 0;
        margin-left: 11px;
        border-radius: 100px;
      }
    }

    .classification-table {
      background: #fff;
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      margin: 10px 10px 0;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
    }

    .two-level-table {
      overflow-y: auto;
      padding: 10px;
      height: 100%;
      box-sizing: border-box;
    }

    /* 父分类样式 */
    .parent-node {
      display: flex;
      align-items: center;
    }

    .expand-icon {
      width: 15px;
      // height: 30rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      margin-right: 5px;
    }

    .parent-name {
      font-weight: 500;
      color: #333;
    }

    /* 子分类样式（固定缩进和前缀） */
    .child-node {
      padding-left: 35rpx;
      /* 固定缩进，区分父分类 */
    }

    .child-name {
      color: #666;
    }

    /* 操作按钮样式 */
    .operation-btns {
      display: flex;
      justify-content: center;
      gap: 8rpx;

      .btn {
        font-weight: 400;
        font-size: 14px;
        color: #0F90FD;
      }
    }

    /* 批量操作按钮 */
    .table-actions {
      margin-top: 20rpx;
      display: flex;
      justify-content: flex-end;
    }

    .detail-foot {
      margin-top: auto;
      position: static;
      bottom: 0;
      background: #ffffff;
      box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
      border-radius: 10px;
      height: 54px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
    }
  }
</style>
